import { Ref, ref, watch } from 'vue';
import { parseLocStringToObject } from './utils/date';

export interface WorldPosition {
  x: number;
  y: number;
  z: number;
}

export interface Config {
  sceneId: Ref<string | null>;
  api: Function;
  onLoaded?: () => void; // 在成功加载后要执行的函数
}

export function useLayoutDevice(config: Config): {
  elementid: string;
  viewer: Ref<any>;
  app: Ref<any>;
  anchorMng: Ref<any>;
  resize: () => void;
  addPrismPoint: (loc: string | WorldPosition) => void;
  addPrismPoints: (locsArr: string[] | WorldPosition[]) => void;
  showAllPrismPoints: () => void;
  clearAllPrismPoints: () => void;
} {
  const viewer = ref();
  const app = ref();
  let viewToken = '';
  const anchorMng = ref(); // 锚点管理器，管理三维椎体

  const elementid = `bfps-${Math.random().toString(36)}`;

  // 监听模型id是否发生改变，若改变则销毁之前的模型，然后再创建新模型。
  watch(
    () => config.sceneId.value,
    (newValue) => {
      if (newValue) {
        destroyApp();
        loadBimface();
      }
    },
    { immediate: true, deep: true },
  );

  // 调整窗口长宽
  function resize() {
    viewer.value.resize(
      document.documentElement.clientWidth,
      document.documentElement.clientHeight - 40,
    );
  }

  // 渲染成功回调
  function successCallback() {
    // 构件GIS场景的App
    const webAppConfig = new window.Glodon.Bimface.Application.WebApplicationGISConfig();
    const domShow = document.getElementById(elementid);
    webAppConfig.domElement = domShow;
    app.value = new window.Glodon.Bimface.Application.WebApplicationGIS(webAppConfig);

    // 获取viewer并加载场景
    viewer.value = app.value.getViewer();
    viewer.value.addScene(viewToken);

    // 初始化三维锚点管理器
    const anchorMngConfig = new window.Glodon.Bimface.Plugins.Anchor.AnchorManagerConfig();
    anchorMngConfig.viewer = viewer.value;
    anchorMng.value = new window.Glodon.Bimface.Plugins.Anchor.AnchorManager(anchorMngConfig);

    // 添加鼠标点击事件
    // viewer.value.addEventListener(
    //   window.Glodon.Bimface.Viewer.ViewerGISEvent.MouseClicked,
    //   function (data) {
    //     addPrismPoint(data.worldPosition);
    //   },
    // );

    if (config.onLoaded) config.onLoaded();
  }

  // 渲染失败回调
  function failureCallback(error) {
    console.log(error);
  }

  function loadBimface() {
    if (!config.sceneId.value) {
      return;
    }

    config
      .api({ key: 'sceneId', value: config.sceneId.value })
      .then((res) => {
        viewToken = res.data;

        // 初始化显示组件
        const loaderConfig = new window.BimfaceSDKLoaderConfig();
        loaderConfig.viewToken = viewToken;
        window.BimfaceSDKLoader.load(loaderConfig, successCallback, failureCallback);
      })
      .catch((error) => {
        console.error(error);
      });
  }

  function addPrismPoint(loc: string | WorldPosition) {
    let prismPointConfig = new window.Glodon.Bimface.Plugins.Anchor.PrismPointConfig();

    if (typeof loc === 'string') {
      prismPointConfig.position = parseLocStringToObject(loc);
    } else {
      prismPointConfig.position = loc;
    }

    prismPointConfig.duration = 1500;
    prismPointConfig.size = 2;
    let prismPoint = new window.Glodon.Bimface.Plugins.Anchor.PrismPoint(prismPointConfig);
    anchorMng.value.addItem(prismPoint);
  }

  function addPrismPoints(locArr: string[] | WorldPosition[]) {
    let prismPoints: any[] = [];
    locArr.forEach((loc) => {
      let prismPointConfig = new window.Glodon.Bimface.Plugins.Anchor.PrismPointConfig();

      if (typeof loc === 'string') {
        prismPointConfig.position = parseLocStringToObject(loc);
      } else {
        prismPointConfig.position = loc;
      }

      prismPointConfig.duration = 1500;
      prismPointConfig.size = 2;
      prismPoints.push(new window.Glodon.Bimface.Plugins.Anchor.PrismPoint(prismPointConfig));
    });
    anchorMng.value.addItems(prismPoints);
  }

  function showAllPrismPoints() {
    anchorMng.value.showAllItems();
  }

  function clearAllPrismPoints() {
    anchorMng.value.clear();
  }

  // 销毁app
  function destroyApp() {
    if (app.value) {
      app.value.destroy();
    }
  }

  return {
    elementid,
    viewer,
    app,
    anchorMng,
    resize,
    addPrismPoint,
    addPrismPoints,
    showAllPrismPoints,
    clearAllPrismPoints,
  };
}
